<template>
  <div style="height: 100%">
    <breadcrumb
      :bread-path-list="[{
        path:'/WitnessTask/HaveWitnessed',
        title: '我的见证'
      }]"
      :show-back-btn-flag="true"
    />
    <div class="witness-report"
       v-loading="printState === 1"
       element-loading-text="拼命加载中"
       element-loading-spinner="el-icon-loading"
  >
    <div ref="demo" style="display: none"></div>
    <div class="witness-report-checkbox">
      <el-tree
        node-key="witnessTaskId"
        @node-click="setShowWitnessTaskId"
        :data="witnessReportProps"
        :props="defaultProps"
        ref="witnessReportRef"
        :default-expanded-keys="['all']"
        :default-checked-keys="defaultCheckedKeys"
        show-checkbox>
      </el-tree>
    </div>
    <div class="witness-report-pdf">
      <WitnessReportPdf
        v-if="showReportPdf && showWitnessTaskId"
        ref="WitnessReportPdf"
        :show="true"
        :pdf-params-baogao="{
          belongId: showWitnessTaskId,
          attachTypeCode: 'WITNESS_REPORT'
        }"
        pdf-box-height="636px"
      />
    </div>
    <!-- 用来打印 -->
<!--    <pdf ref="pdfPrintss" style="display: none" :src="src"-->
<!--         @error="error"-->
<!--         @progress="loadedRatio = $event"-->
<!--         @num-pages="pageCount = $event"-->
<!--         @page-loaded="currentPage = $event" />-->
    <div class="pdf-btns">
      <!-- 当附件id为空时，禁用按钮 -->
      <el-button type="primary" plain class="ui-pl10" :disabled="false" @click="print">
        打印
      </el-button>
      <el-button
        type="primary"
        :disabled="false"
        @click="pdfDownloadFn"
        >保存{{isDownloading ? '中...' : ''}}</el-button>
    </div>
  </div>
  </div>
</template>

<script>
import WitnessReportPdf from "../../../components/WitnessReportPdf.vue";
import { viewList } from "@/api/api"; // 见证书预览pdf组件
import pdf from "vue-pdf-cs";
import CMapReaderFactory from "vue-pdf/src/CMapReaderFactory.js";
import axios from "axios";

export default {
  name: "WitnessReport",
  components: { WitnessReportPdf, pdf },
  data: () => ({
    src:'',
    defaultCheckedKeys: [], // 默认选的标包
    witnessReportProps: [], // 树状选择数据
    defaultProps: {
      children: "bidsectionInfoList",
      label: "label"
    },
    pdfVisibleBaogao: true,
    pdfParamsBaogaoList: [],
    showWitnessTaskId:'',
    isDownloading: false,
    printUrl: "",
    downloadUrl: "",
    printState: 0, // 0 未加载, 1: 正在加载; 2: 加载完成
    showReportPdf: true
  }),

  computed: {
    projectCode() {
      return this.$route.query.projectCode;
    }
  },

  created() {
    this.getTaskDetailList(this.projectCode);
  },

  mounted() {
    try {
      setTimeout(() => {
        this.$refs.witnessReportRef.$el.getElementsByClassName('el-tree-node__children')[0].childNodes[0].style.color='#1890ff';
      },1000)
    } catch (e) {
      console.error(e);
    }
  },

  watch: {
    showWitnessTaskId(){
    this.showReportPdf = false;
    this.$nextTick(() => {
      this.showReportPdf = true;
    })
    }
  },

  methods: {
    // 修改显示的pdf文件
    setShowWitnessTaskId(data, node, el){
      if(data.witnessTaskId !== 'all'){
        const childNodes = el.$el.parentNode.childNodes;
        childNodes.forEach(item => {
          if(item === el.$el){
            item.style.color = '#1890ff';
          } else {
            item.style.color = '';
          }
        })
        this.showWitnessTaskId = data.witnessTaskId;
      }
    },

    // 获取当前项目的所有的标包
    async getTaskDetailList(projectCode) {
      const { data, success, message } = await viewList({
        currentPage: 1,
        pageSize: 10,
        search: projectCode,
        witnessSubTaskStatusEnum: "WITNESS_FINISHED",
        type:2
      });

      if (success) {
        data.result.forEach((proItem) => {
          const proObj = proItem.data;
          proObj.label = proObj.projectName;
          proObj.witnessTaskId = "all";
          proObj.bidsectionInfoList = [];
          proObj.bidSectionVOList.result.forEach((bidItem) => {
            const bidObj = bidItem.data;
            bidItem.pageOpers.forEach((val) => {
              bidObj[val.code] = true;
            });
            bidObj.label = bidObj.bidSectionName;
            proObj.bidsectionInfoList.push(bidObj);
          });
          this.$delete(proObj, "bidSectionVOList");
          this.witnessReportProps.push(proObj);

          if (this.witnessReportProps[0]?.bidsectionInfoList?.length > 0) {
            this.showWitnessTaskId = this.witnessReportProps[0].bidsectionInfoList[0].witnessTaskId
          }
        });
      } else {
        this.$message({
          type: "error",
          message: message || "获取数据失败，请稍后再试",
          single: true
        });
      }
    },


    // 返回选中的项目的id
    getCheckedTask() {
      const keys = this.$refs.witnessReportRef.getCheckedKeys();
      return keys.length === 0 ? this.witnessReportProps[0].bidsectionInfoList.map(item => item.witnessTaskId) :keys.filter(item => item !== 'all')
    },

    // 设置默认选中第一个
    setDefaultCheckedKeysFist(id) {
      this.defaultCheckedKeys.push(id);
    },


    // 打印
    async print() {
      try {
        const taskIdList = this.getCheckedTask();
        const instance = axios.create({
          contentType: "application/json;charset=UTF-8",
          responseType: "blob"
        });
        const res = await instance.get(`/gdw/gz/witness/record/mergePdf?belongIds=${taskIdList.join(',')}`);
        const csvData = new Blob([res.data], { type: "application/pdf" });
        this.src = window.URL.createObjectURL(csvData);
        const iframe = document.createElement("iframe");
        iframe.src = this.src;
        iframe.onload = () => {
          iframe.contentWindow.print()
        }
        this.$refs.demo.innerHTML = '';
        this.$refs.demo.appendChild(iframe);
        window.URL.revokeObjectURL(this.src);
      } catch (e) {
        console.error(e);
      }
    },

    async pdfDownloadFn() {
      try {
        const taskIdList = this.getCheckedTask();
        if(this.isDownloading){
          return
        }
        this.isDownloading = true;
        const instance = axios.create({
          contentType: "application/json;charset=UTF-8",
          responseType: "blob"
        });
        const res = await instance.get(`/gdw/gz/witness/record/mergePdf?belongIds=${taskIdList.join(',')}`);
        const fileName = "见证报告.pdf";
        const csvData = new Blob([res.data], { type: "application/pdf" });
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(csvData, fileName);
        } else {
          const a = document.createElement("a");
          document.body.appendChild(a);
          a.style = "display: none";
          const url = window.URL.createObjectURL(csvData);
          a.href = url;
          a.download = fileName;
          a.click();
          a.remove();
          window.URL.revokeObjectURL(url);
        }
        this.$message.success('保存成功');
      } catch (e) {
        console.error(e);
      }finally {
        this.isDownloading = false;
      }
    },

    error(e) {
      console.log(e);
    }
  }
};
</script>

<style lang="scss">
.witness-report {
  display: flex;
  width: 100%;
  height:calc(100% - 44px);
  padding: 10px 0 54px 0;
  box-sizing: border-box;

  .witness-report-checkbox {
    width: 300px;
    margin-right: 20px;
    height: 100%;
    background: #FFFFFF;
  }

  .witness-report-pdf {
    width: calc(100% - 320px);
    height: 100%;
    overflow-y: auto;
    background: #eee;
    padding: 20px 40px;
    box-sizing: border-box;

    .witnessPdf {
      height: auto;
      margin-top: 0;

      .pdf-btns {
        display: none;
      }

      .pdf-box {
        padding: 0;
        height: auto !important;
      }
    }
  }


}

</style>
<style lang="scss" scoped>

::v-deep .el-tree-node__content {
  height: auto;
  white-space: pre-wrap;
  &:hover{
    color: rgb(24, 144, 255);
  }
}

.witnessPdf-dayin {
  display: none;
}

.pdf-btns {
  position: absolute;
  right: 0px;
  bottom: 0px;
  background: #fff;
  width: 100%;
  text-align: right;
  padding: 10px;
}
</style>
